<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="费用编号" prop="costManageCode">
        <el-input
          v-model="queryParams.costManageCode"
          placeholder="请输入费用编号"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="销售单编号" prop="salesOrderCode">
        <el-input
          v-model="queryParams.salesOrderCode"
          placeholder="请输入销售单编号"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="支出人" prop="payeeName">
        <el-input
          v-model="queryParams.payeeName"
          placeholder="请输入支出人名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="支出时间" prop="payeeTime">
        <el-date-picker clearable
                        v-model="queryParams.payeeTime"
                        type="date"
                        value-format="yyyy-MM-dd"
                        placeholder="请选择支出时间"
        >
        </el-date-picker>
      </el-form-item>
      <el-form-item label="费用类型" prop="costType">
        <el-cascader
          v-model="queryParams.costType"
          :options="costTypeList"
          @change="handleChangeQuery"
        ></el-cascader>
      </el-form-item>
      <el-form-item label="费用金额" prop="costPrice">
        <el-input
          v-model="queryParams.costPrice"
          placeholder="请输入费用金额"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="费用单据编号" prop="costInvoiceNo">
        <el-input
          v-model="queryParams.costInvoiceNo"
          placeholder="请输入费用单据编号"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['wm:costManage:add']"
        >新增
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['wm:costManage:edit']"
        >修改
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['wm:costManage:remove']"
        >删除
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['wm:costManage:export']"
        >导出
        </el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="costManageList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center"/>
      <el-table-column label="费用编号" align="center" prop="costManageCode"/>
      <el-table-column label="销售单编号" align="center" prop="salesOrderCode"/>
      <el-table-column label="销售单名称" align="center" prop="salesOrderName"/>
      <el-table-column label="支出人名称" align="center" prop="payeeName"/>
      <el-table-column label="支出时间" align="center" prop="payeeTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.payeeTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="费用类型" align="center" prop="costType">
        <template slot-scope="scope">
          {{ getChangeType(scope.row.costType) }}
        </template>
      </el-table-column>
      <el-table-column label="费用金额" align="center" prop="costPrice"/>
      <el-table-column label="费用单据编号" align="center" prop="costInvoiceNo"/>
      <el-table-column label="附件信息" align="center" prop="costAppendix"/>
      <el-table-column label="备注" align="center" prop="remark"/>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['wm:costManage:edit']"
          >修改
          </el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['wm:costManage:remove']"
          >删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改费用管理对话框 -->
    <el-dialog :close-on-click-modal="false" :title="title" :visible.sync="open" width="900px" class="form-container">
      <el-form
        inline
        ref="form"
        size="small"
        :model="form"
        :rules="rules"
        :disabled="isView"
        label-width="7em"
        class="add-form"
      >
        <el-row>
          <el-col :span="12">
            <el-form-item label="费用编号" prop="costManageCode">
              <div style="display: flex; align-items: center">
                <el-input
                  v-model="form.costManageCode"
                  placeholder="请输入费用编号"
                />
                <!-- 是否自动生成开关 -->
                <el-switch
                  style="margin-left: 10px"
                  @change="onAutoGenerateChange"
                  v-model="form.isAutoGenerate"
                />
                <span style="flex: 1">自动生成</span>
              </div>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="销售单编号" prop="salesOrderCode">
              <el-select
                v-model="form.salesOrderCode"
                filterable
                :remote="true"
                placeholder="请选择销售单"
                style="width: 86%"
                :remote-method="querySearch"
                @change="handleSelectInput"
                :loading="salesLoading"
              >
                <el-option
                  v-for="item in salesList"
                  :key="item.value"
                  :label="item.salseOrderCode"
                  :value="item.salseOrderName"
                />
              </el-select>
              <i
                class="el-icon-search"
                v-if="!isView"
                @click="showSelectSalesDialog = true"
                style="
                margin-left: 10px;
                font-size: 20px;
                font-weight: bold;
                cursor: pointer;
              "
              ></i>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="8">
            <el-form-item label="销售单名称" prop="salesOrderName">
              <el-input disabled v-model="form.salesOrderName"/>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="支出人名称" prop="payeeName">
              <el-select
                v-model="form.payeeName"
                placeholder="请选择支出人名称"
                filterable
                remote
                reserve-keyword
                :remote-method="remoteMethod"
                :loading="searchLoading"
                @blur="delKeyMethod"
              >
                <el-option
                  v-for="item in userList"
                  :key="item.userId"
                  :label="item.userName"
                  :value="item.userName"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="支出时间" prop="payeeTime">
              <el-date-picker clearable
                              v-model="form.payeeTime"
                              type="date"
                              value-format="yyyy-MM-dd"
                              placeholder="请选择支出时间"
              >
              </el-date-picker>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="8">
            <el-form-item label="费用类型" prop="costType">
              <el-cascader
                v-model="form.costType"
                :options="costTypeList"
                @change="handleChange"
              ></el-cascader>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="费用金额" prop="costPrice">
              <el-input v-model="form.costPrice" placeholder="请输入费用金额"/>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="费用单据编号" prop="costInvoiceNo">
              <el-input v-model="form.costInvoiceNo" placeholder="请输入费用单据编号"/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="附件信息" prop="costAppendix">
              <file-upload v-model="form.costAppendix"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="备注" prop="remark">
              <el-input type="textarea" v-model="form.remark" placeholder="请输入备注"/>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
    <el-dialog :close-on-click-modal="false" width="1100px" :visible.sync="showSelectSalesDialog">
      <sales :isComponent="true" @select="onSelectSales"/>
    </el-dialog>
  </div>
</template>

<script>
import {
  listCostManage,
  getCostManage,
  delCostManage,
  addCostManage,
  updateCostManage,
  treeSelectCostType, getCostType
} from '@/api/mes/wm/costManage'
import { genCode } from '@/api/system/autocode/rule'
import sales from '@/views/mes/sale/index.vue'
import { allUser } from '@/api/system/user'
import request from '@/utils/request'

export default {
  name: 'CostManage',
  components: { sales },
  data() {
    return {
      costTypeName: '',
      salesLoading: false,
      showSelectSalesDialog: false,
      salesList: [],
      costTypeList: [],
      allCostTypeList: [],
      userList: [],
      searchLoading: false,
      isView: false,
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 费用管理表格数据
      costManageList: [],
      // 弹出层标题
      title: '',
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        costManageCode: null,
        salesOrderCode: null,
        salesOrderName: null,
        payeeName: null,
        payeeTime: null,
        costType: null,
        costPrice: null,
        costInvoiceNo: null,
        costAppendix: null
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        costManageCode: [
          { required: true, message: '费用管理编号不能为空', trigger: 'blur' }
        ],
        salesOrderCode: [
          { required: true, message: '销售单编号不能为空', trigger: 'blur' }
        ]
      }
    }
  },
  created() {
    this.getList()
    this.getAllUser()
    this.getTreeCostType()
  },
  methods: {
    /** 查询费用管理列表 */
    getList() {
      this.loading = true
      listCostManage(this.queryParams).then(response => {
        this.costManageList = response.rows
        this.total = response.total
        this.loading = false
      })
    },
    getAllUser() {
      allUser().then(response => {
        this.userList = response.data.map(item => {
          return {
            userId: item.userId,
            userName: item.userName
          }
        })
      })
    },
    getTreeCostType() {
      treeSelectCostType().then(response => {
        this.costTypeList = response.data.map(item => {
          return {
            label: item.label,
            value: item.value,
            children: item.children
          }
        })
      }),
        getCostType().then(response => {
          this.allCostTypeList = response.data.map(item => {
            return {
              itemTypeName: item.itemTypeName,
              itemTypeCode: item.itemTypeCode
            }
          })
        })
    },
    remoteMethod(query) {
      if (query !== '') {
        this.searchLoading = true
        setTimeout(() => {
          this.searchLoading = false
          this.userList = this.userList.filter(item => {
            return item.userName.toLowerCase()
              .indexOf(query.toLowerCase()) > -1
          })
        }, 200)
      } else {
        this.userList = []
      }
    },
    getChangeType(val) {
      for (var i = 0; i < this.allCostTypeList.length; i++) {
        if (this.allCostTypeList[i].itemTypeCode == val) {
          return this.allCostTypeList[i].itemTypeName
        }
      }
    },
    delKeyMethod() {
      this.getAllUser()
    },
    handleChange(val) {
      this.form.costType = val[1]
    },
    handleChangeQuery(val) {
      this.queryParams.costType = val[1]
    },
    // 取消按钮
    cancel() {
      this.open = false
      this.reset()
    },
    // 表单重置
    reset() {
      this.form = {
        costManageId: null,
        costManageCode: null,
        salesOrderCode: null,
        salesOrderName: null,
        payeeName: null,
        payeeTime: null,
        costType: null,
        costPrice: null,
        costInvoiceNo: null,
        costAppendix: null,
        remark: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null
      }
      this.resetForm('form')
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm('queryForm')
      this.handleQuery()
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.costManageId)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset()
      this.open = true
      this.title = '添加费用管理'
      this.form.payeeName = this.$store.getters.name
      this.form.isAutoGenerate = true;
      this.onAutoGenerateChange();
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset()
      const costManageId = row.costManageId || this.ids
      getCostManage(costManageId).then(response => {
        this.form = response.data
        this.open = true
        this.title = '修改费用管理'
      })
    },
    querySearch(query) {
      if (query !== '') {
        let params = {
          salesOrderName: query
        }
        request({
          url: '/mes/wm/salseOrder/list',
          method: 'get',
          params
        }).then((res) => {
          this.salesLoading = false
          this.salesList = res.rows
        })
      } else {
        this.salesList = []
      }
    },
    handleSelectInput(val) {
      const sales = this.salesList.find((item) => item.salseOrderCode === val)
      this.onSelectSales(sales)
    },
    onSelectSales(sales) {
      this.showSelectSalesDialog = false
      this.form.salesOrderCode = sales.salseOrderCode
      this.form.salesOrderName = sales.salseOrderName
    },
    onAutoGenerateChange(val) {
      if (this.form.isAutoGenerate) {
        genCode('COSE_MANAGE_CODE').then((res) => {
          this.$set(this.form, 'costManageCode', res)
        })
      } else {
        this.form.costManageCode = ''
      }
    },

    /** 提交按钮 */
    submitForm() {
      this.$refs['form'].validate(valid => {
        if (valid) {
          if (this.form.costManageId != null) {
            updateCostManage(this.form).then(response => {
              this.$modal.msgSuccess('修改成功')
              this.open = false
              this.getList()
            })
          } else {
            addCostManage(this.form).then(response => {
              this.$modal.msgSuccess('新增成功')
              this.open = false
              this.getList()
            })
          }
        }
      })
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const costManageIds = row.costManageId || this.ids
      this.$modal.confirm('是否确认删除费用管理编号为"' + costManageIds + '"的数据项？').then(function() {
        return delCostManage(costManageIds)
      }).then(() => {
        this.getList()
        this.$modal.msgSuccess('删除成功')
      }).catch(() => {
      })
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('mes/wm/costManage/export', {
        ...this.queryParams
      }, `costManage_${new Date().getTime()}.xlsx`)
    }
  }
}
</script>
<style lang="scss" scoped>
.form-container {
  ::v-deep {
    .el-form-item {
      min-width: 290px;
      margin-bottom: 15px;
      display: inline-flex;
      align-items: center;
    }

    .el-form-item__content {
      display: inline-flex;
      align-items: center;
    }

    .el-input {
      width: 160px;
    }
  }
}
</style>
